package root.electronclass.electronclass.other

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.net.Uri
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.coroutineScope
import com.blankj.utilcode.util.GsonUtils
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.event.WebSocketEvent
import root.electronclass.electronclass.common.util.QRCodeUtil
import root.electronclass.electronclass.R
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.entity.WebSocketData
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.databinding.ActivityScanBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.setup
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.EcardAttnDTO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import retrofit2.Call
import java.io.ByteArrayOutputStream


/**
 * 扫码认证
 */
class ScanActivity : ViewBindingActivity<ActivityScanBinding>() {
    private var mWebSocketService: WebSocketService? = null

    override fun init() {
        if(!EventBus.getDefault().isRegistered(this)){//是否注册eventbus的判断
            EventBus.getDefault().register(this);
        }
        binding.top.setup(lifecycle, "")
        binding.top.title.visibility = View.GONE

        binding.back.back.setOnClickListener {
            finish()
        }
        startWebSocketService()
    }

    /**
     * 开启并绑定WebSocket服务
     */
    fun startWebSocketService() {
        val bindIntent = Intent(this@ScanActivity, WebSocketService::class.java)
        startService(bindIntent)
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE)
    }

    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            //服务与活动成功绑定
            mWebSocketService = (iBinder as WebSocketService.JWebSocketClientBinder).service
            Log.d("WebSocketService", "WebSocket服务与Application成功绑定")
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            //服务与活动断开
            mWebSocketService = null
            Log.d("WebSocketService", "WebSocket服务与Application成功断开: ")
        }
    }

    // 接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWebSocketEvent(event: WebSocketEvent) {
        // 处理数据
        try {
            val webSocketVo: WebSocketData = GsonUtils.fromJson(event.message, WebSocketData::class.java)
            when (webSocketVo.msgType) {
                1 -> {
                    val bitmap = QRCodeUtil.createQRCodeBitmap(webSocketVo.data, 460, 460) ?: return
                    binding.scan.setImageURI(getImageUri(bitmap))
                }
                2 -> {
                    GlobalParameter.setEventType(3)
                    GlobalParameter.setCardNum(null)
                    RestManager.getInstance().initService()
                    RestManager.getInstance().token = webSocketVo.data
                    //考勤打卡
                    if (intent.getIntExtra("RequestCode", 0) == AttestationActivity.ATTENDANCE) {
                        RestManager.getInstance().initRest().saveAttn(EcardAttnDTO()).enqueue(object : CallbackNext<BaseResponse<Any>>(mDialogViewModel) {
                            override  fun onSuccessful(call: Call<BaseResponse<Any>>?, response: BaseResponse<Any>?) {
                                Log.i("CardActivity", "onSuccessful: ${response}")
                                binding.resultCl.isVisible = true
                                if (response?.code == 200){
                                    binding.resultTv.text = "打卡成功"
                                    binding.result.setImageResource(R.mipmap.success_icon)
                                    binding.resultTv1.text = "恭喜你，已完成考勤打卡"
                                }else{
                                    binding.resultTv.text = "打卡失败"
                                    binding.result.setImageResource(R.mipmap.fault_icon)
                                    binding.resultTv1.text = response?.msg
                                }
                                lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
                                    delay(3000)
                                    setResult(Activity.RESULT_OK)
                                    finish()
                                }
                            }

                            override fun onError(call: Call<BaseResponse<Any>>?, response: BaseResponse<Any>?) {
                                binding.resultTv.text = "打卡失败"
                                binding.result.setImageResource(R.mipmap.fault_icon)
                                binding.resultTv1.text = response?.msg
                                lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
                                    delay(3000)
                                    setResult(Activity.RESULT_OK)
                                    finish()
                                }
                            }

                        })
                    } else {
                        toast("登录成功")
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                    setResult(Activity.RESULT_OK)
                    finish()
                }
            }

        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

   private fun getImageUri(inImage: Bitmap): Uri {
        val bytes = ByteArrayOutputStream()
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
        val path: String = MediaStore.Images.Media.insertImage(contentResolver, inImage, "Title", null)
        return Uri.parse(path)
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
        EventBus.getDefault().unregister(this)
        unbindService(serviceConnection)
    }

    /**
     * 断开连接
     */
    private fun closeConnect() {
        try {
            if (null != mWebSocketService) {
                mWebSocketService!!.closeConnect()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            mWebSocketService = null
        }
    }

}